package de.tv.weatherox;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class JsonForecastServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EntityManager em = null;
        String maxResultsAsString = StringUtils.strip(request.getPathInfo(), "/");
        int maxResults = NumberUtils.toInt(maxResultsAsString);
        if(maxResults == 0 || maxResults > 31) {
            maxResults = 31;
        }
        try {
            em = EMF.get().createEntityManager();
            Query q = em.createQuery("SELECT f FROM Forecast f WHERE f.date >= :date ORDER BY f.date asc");
            q.setParameter("date", DateUtils.truncate(new Date(), Calendar.DATE));
            q.setMaxResults(maxResults);
            @SuppressWarnings("unchecked")
            List<Forecast> forecasts = q.getResultList();
            Type listType = new TypeToken<List<Forecast>>() {}.getType();
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").excludeFieldsWithoutExposeAnnotation().create();
            response.getWriter().append(gson.toJson(forecasts, listType));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
